package com.liangtian.mdm.system.uniformSelect.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.listener.CacheUtil;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.uniformSelect.model.SysUniformSelect;
import com.liangtian.mdm.system.uniformSelect.service.SysUniformSelectService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/sysUniformSelect")
public class SysUniformSelectController extends BaseController {

    @Autowired
    private SysUniformSelectService sysUniformSelectService;

    // 日志服务接口对象
    @Autowired
    SysLogService sysLogService;
    @Autowired
    private CacheUtil cacheUtil;

    // Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    @ResponseBody
    @RequestMapping(value = "/getUniformSelectLstByCond", method = RequestMethod.POST)
    public JSONObject getUniformSelectLstByCond(HttpServletRequest request, SysUniformSelect query) {
//		Map paramMap = RequestUtils.paramToMap(request, SysUniformSelect.class, false);
//		PageInfo pageInfo = SysUniformSelectService.getUniformSelectLstByCond(paramMap);
        List<SysUniformSelect> queryLst = sysUniformSelectService.getUniformSelectLstByCond(query);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("queryLst", queryLst);
        return jsonObject;
    }

    @RequestMapping(value = "/insertUniformSelect", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertUniformSelect(HttpServletRequest request, SysUniformSelect query) {
        // 获取当前日期
        Date date = new Date();
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        int count = sysUniformSelectService.insertUniformSelect(query);
		/*// ==============================记录操作日志start===============================================
		SysLog sysLog = new SysLog();
		sysLog.setUserName(user.getUserName());
		sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
		sysLog.setOperationDate(date);
		if (count > 0) {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",新增高级查询设置成功");
		} else {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",新增高级查询设置失败");
		}
		sysLogServiceImpl.insertLog(sysLog);
		// ==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("新增高级查询设置",
                SysLogEnum.SYS_UNIFORMSELECT.getCode(), SysLogEnum.XZ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    @ResponseBody
    @RequestMapping(value = "/checkGJQueryCount", method = RequestMethod.POST)
    public JSONObject checkGJQueryCount(HttpServletRequest request, SysUniformSelect query) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = sysUniformSelectService.checkGJQueryCount(query);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/updateGJQueryByAttrId", method = RequestMethod.POST)
    public ResultObject updateGJQueryByAttrId(SysUniformSelect query) {
        ResultObject result = null;
        try {
            sysUniformSelectService.updateGJQueryByAttrId(query);
            result = new ResultObject(1, "操作成功", "操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultObject(2, "操作成功", "操作失败");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getGJQueryByAttrId", method = RequestMethod.POST)
    public String getGJQueryByAttrId(SysUniformSelect query) {
        SysUniformSelect select = null;
        try {
            select = sysUniformSelectService.getGJQueryByAttrId(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(select);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteGJQueryByAttrIds", method = RequestMethod.POST)
    public ResultObject deleteGJQueryByAttrIds(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids))
            return null;
        Map<String, Object> map = new HashMap<>();
        map.put("idList", ids.split(","));
        int ret = sysUniformSelectService.deleteGJQueryByAttrIds(map);
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "删除成功", "删除失败");
        return result;
    }

    //替换生成的属性列
    @ResponseBody
    @RequestMapping(value = "/getModelAttr", method = RequestMethod.POST)
    public String getModelAttr(HttpServletRequest request) {
        String model_id = request.getParameter("model_id");
        String attr_id = request.getParameter("attr_id");
        String unit_model_id = request.getParameter("unit_model_id");
        Model unitmodel = cacheUtil.getModel(unit_model_id);
//		Model model = cacheUtil.getModel(model_id);
        AttrConfig conf = cacheUtil.getAttrConfig(model_id, attr_id);
        List<AttrConfig> resPopConfig = new ArrayList<AttrConfig>(); //返回的结果
        for (String confCol : conf.getDataSourceColumn().split(",")) {
            AttrConfig attrConfig = cacheUtil.getAttrConfig(unit_model_id, confCol);
            resPopConfig.add(attrConfig);
        }

        String sb = this.spellPopJspByGjQuery(resPopConfig, unitmodel);
        return sb.toString();

    }

    public String spellPopJspByGjQuery(List<AttrConfig> jspAttrLst, Model model) {
        StringBuilder sb = new StringBuilder();
        sb.append("<th data-field='' data-checkbox='true'></th> \r\n");
        for (AttrConfig ac : jspAttrLst) {
            sb.append("<th data-field='").append(ac.getAttrColumn().toLowerCase()).append("' ")
                    .append(" data-sortable='true' ");
            String attrType = ac.getAttrType();
            if (("selectList").equals(attrType) || ("radioType").equals(attrType) || ("checkBoxType").equals(attrType)) {
                sb.append("data-filter-control='select'");
            } else {
                sb.append("data-filter-control='input' width='20%'");
            }
            sb.append(">").append(ac.getAttrName());
            sb.append("</th> \r\n");
        }
        return sb.toString();
    }

}
